package com.yidingdui.controller;

import com.yidingdui.domain.dto.AsyncGenerateRequest;
import com.yidingdui.domain.dto.Image3DDto;
import com.yidingdui.domain.entity.ModelHistory;
import com.yidingdui.domain.vo.AsyncGenerateResponse;
import com.yidingdui.domain.vo.ImageVo;
import com.yidingdui.domain.vo.ModelHistoryVO;
import com.yidingdui.domain.vo.Resultdata;
import com.yidingdui.service.Image3DService;
import com.yidingdui.service.ModelHistoryService;
import com.yidingdui.util.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/image3d")
@RequiredArgsConstructor
public class Image3DController {

    private final Image3DService image3DService;
    private final ModelHistoryService modelHistoryService;

    /**
     * 异步生成3D模型（文字描述）
     */
    @PostMapping("/generateAsync")
    public Resultdata<AsyncGenerateResponse> generateAsync(@RequestBody AsyncGenerateRequest request) {
        Long userId = UserContext.getUser();
        String taskId = java.util.UUID.randomUUID().toString();
        
        // 创建历史记录
        modelHistoryService.createTask(taskId, userId, request.getPrompt(), null, 
                request.getEnablePBR(), request.getResultFormat());
        
        // 异步执行生成任务
        image3DService.generateAsync(taskId, request.getPrompt(), request.getEnablePBR(), request.getResultFormat());
        
        AsyncGenerateResponse response = new AsyncGenerateResponse(taskId, "RUN", "任务已提交，正在生成中...");
        return Resultdata.success(response);
    }

    /**
     * 异步生成3D模型（图片上传）
     */
    @PostMapping("/generateFromImageAsync")
    public Resultdata<AsyncGenerateResponse> generateFromImageAsync(
            @RequestPart("request") AsyncGenerateRequest request,
            @RequestPart(value = "imageFile", required = false) MultipartFile imageFile) {
        Long userId = UserContext.getUser();
        String taskId = java.util.UUID.randomUUID().toString();
        
        // 创建历史记录
        modelHistoryService.createTask(taskId, userId, null, 
                imageFile != null ? imageFile.getOriginalFilename() : null,
                request.getEnablePBR(), request.getResultFormat());
        
        // 异步执行生成任务
        image3DService.generateFromImageAsync(taskId, request.getEnablePBR(), request.getResultFormat(), imageFile);
        
        AsyncGenerateResponse response = new AsyncGenerateResponse(taskId, "RUN", "任务已提交，正在生成中...");
        return Resultdata.success(response);
    }

    /**
     * 查询任务状态
     */
    @GetMapping("/status/{taskId}")
    public Resultdata<ModelHistoryVO> getTaskStatus(@PathVariable String taskId) {
        ModelHistory history = modelHistoryService.findByTaskId(taskId);
        if (history == null) {
            return Resultdata.error("404", "任务不存在");
        }
        
        ModelHistoryVO vo = new ModelHistoryVO();
        com.yidingdui.util.BeanUtils.copyProperties(history, vo);
        return Resultdata.success(vo);
    }

    /**
     * 查询用户历史记录
     */
    @GetMapping("/history")
    public Resultdata<List<ModelHistoryVO>> getUserHistory() {
        Long userId = UserContext.getUser();
        List<ModelHistoryVO> histories = modelHistoryService.findByUserId(userId);
        return Resultdata.success(histories);
    }

    // 保留原有接口用于兼容
    @PostMapping("/getImageOfPrompt")
    public Resultdata<ImageVo> getImage3DOfPrompt(@RequestBody Image3DDto image3DDto){
        return image3DService.getImage3DOfPrompt(image3DDto);
    }

    @PostMapping("/getImageOfImage")
    public Resultdata<ImageVo> getImage3DOfImage(@RequestPart("image3DDto") Image3DDto image3DDto,
                                                @RequestPart(value = "imageFile", required = false) MultipartFile imageFile){
        return image3DService.getImage3DOfImage(image3DDto, imageFile);
    }
}